package com.weblog.weblog.jwt.handler;

import com.weblog.weblog.common.enums.ResponseCodeEnum;
import com.weblog.weblog.common.utils.Response;
import com.weblog.weblog.jwt.exception.UsernameOrPasswordNullException;
import com.weblog.weblog.jwt.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 * @class_name RestAuthenticationFailureHandler
 * @date 2023年09月15日 20:38
 */
@Slf4j
@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        log.warn("AuthenticationException: ", exception);

        if (exception instanceof UsernameOrPasswordNullException){

            ResultUtils.fail(response , Response.fail(exception.getMessage()));
        }else if (exception instanceof BadCredentialsException){

            ResultUtils.fail(response ,Response.fail(ResponseCodeEnum.USERNAME_OR_PWD_ERROR));
        }

        ResultUtils.fail(response,Response.fail(ResponseCodeEnum.LOGIN_FAIL));
    }
}
